<template>
	<div class="div body">
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			class="demo-ruleForm"
			:size="formSize"
			status-icon
		>
			<el-form-item label="当前密码:" prop="password">
				<el-input
					v-model="ruleForm.password"
					placeholder="请输入当前密码"
					type="password"
				></el-input>
			</el-form-item>
			<el-form-item label="新密码:" prop="newPassword1">
				<el-input
					v-model="ruleForm.newPassword1"
					placeholder="请输入新密码"
					type="password"
				></el-input>
			</el-form-item>
			<el-form-item label="确认密码:" prop="newPassword2">
				<el-input
					type="password"
					v-model="ruleForm.newPassword2"
					placeholder="请再次输入新密码"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm(ruleFormRef)">
					修改密码
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { useInfoStore } from "../store/userInfo";
import { useTabsStore } from "../store/tabs";
import { userPwd } from "../api/user";
import router from "../router";
const store = useInfoStore();
const tabsStore = useTabsStore();

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
	password: "",
	newPassword1: "",
	newPassword2: "",
});

const validatePass2 = (rule: any, value: any, callback: any) => {
	if (value === "") {
		callback(new Error("请再次输入新密码!"));
	} else if (value !== ruleForm.newPassword1) {
		callback(new Error("两次密码不一致!"));
	} else {
		callback();
	}
};

const rules = reactive<FormRules>({
	password: [{ required: true, message: "请输入当前密码!", trigger: "blur" }],
	newPassword1: [{ required: true, message: "请输入新密码!", trigger: "blur" }],
	newPassword2: [
		{
			required: true,
			validator: validatePass2,
			trigger: "blur",
		},
	],
});

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			console.log("submit!");
			let { objectId, sessionToken } = JSON.parse(
				localStorage.getItem("userInfo")!
			).userInfo;
			console.log(ruleForm.newPassword2);

			userPwd(
				objectId,
				ruleForm.password,
				ruleForm.newPassword2,
				sessionToken
			).then(() => {
				ElMessage({
					message: "修改成功,请重新登录",
					type: "success",
				});
				store.userInfo = null;
				setTimeout(() => {
					localStorage.removeItem("userInfo");
					router.push("/login");
				}, 1000);
			});
		} else {
			console.log("error submit!", fields);
		}
	});
};
</script>

<style scoped lang="scss">
.div {
	display: flex;
}
.el-form {
	width: 400px;
	.el-form-item {
		margin-bottom: 14px;
	}
}
</style>
